package com.jixi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jixi.common.exception.PowerFailedException;
import com.jixi.common.result.PageResult;
import com.jixi.common.result.Result;
import com.jixi.common.utils.Md5Util;
import com.jixi.mapper.AccountMapper;
import com.jixi.mapper.CompanyMapper;
import com.jixi.mapper.CooperateSchoolCompanyMapper;
import com.jixi.mapper.EducationMapper;
import com.jixi.pojo.dto.CompanyRegisterDto;
import com.jixi.pojo.entity.Account;
import com.jixi.pojo.entity.Company;
import com.jixi.pojo.entity.CooperateSchoolCompany;
import com.jixi.pojo.entity.Education;
import com.jixi.service.CompanyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {
	
	@Autowired
	private CompanyMapper companyMapper;
	
	@Autowired
	private EducationMapper educationMapper;
	
	@Autowired
	private CooperateSchoolCompanyMapper cooperateSchoolCompanyMapper;
	
	@Autowired
	private AccountMapper accountMapper;
	
	/**
	 * 注册餐饮公司
	 *
	 * @param companyRegisterDto 注册信息
	 * @return 注册结果
	 */
	@Override
	public Result companyRegister(CompanyRegisterDto companyRegisterDto) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		Company company = new Company();
		BeanUtils.copyProperties(companyRegisterDto, company);
		log.info("注册信息：{}", company);
		company.setIsDeleted(0);
		company.setCompanyPassword(Md5Util.getMD5String(company.getCompanyPassword()));
		companyMapper.insert(company);
		return Result.success("注册成功");
	}
	
	/**
	 * 获取餐饮公司列表
	 *
	 * @param pageNum       页码
	 * @param pageSize      每页数量
	 * @param companyName   公司名
	 * @param principalName 负责人名
	 * @param status        公司状态
	 * @return 公司列表
	 */
	@Override
	public Result<PageResult> companyPage(
			Integer pageNum,
			Integer pageSize,
			String companyName,
			String principalName,
			Integer status
	) {
		//分页构造器
		Page<Company> pageInfo = new Page<>(pageNum, pageSize);
		
		//条件构造器
		LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper.eq(Company::getIsDeleted, 0);
		//添加可能有的过滤条件
		queryWrapper.like(companyName != null && !companyName.trim().isEmpty(), Company::getCompanyName, companyName);
		queryWrapper.like(principalName != null && ! principalName.trim().isEmpty(), Company::getPrincipalName, principalName);
		queryWrapper.eq(status != null, Company::getStatus, status);
		//执行分页查询
		companyMapper.selectPage(pageInfo, queryWrapper);
		PageResult pageResult = new PageResult(pageInfo.getTotal(), pageInfo.getRecords());
		return Result.success(pageResult);
	}
	
	/**
	 * 获取餐饮公司信息
	 *
	 * @param companyId 公司id
	 * @return 公司信息
	 */
	@Override
	public Company getCompanyInfo(Long companyId) {
		//只查未删除的
		LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Company::getIsDeleted, 0);
		queryWrapper.eq(Company::getCompanyId, companyId);
		Company company = companyMapper.selectOne(queryWrapper);
		return company;
	}
	
	/**
	 * 餐饮公司重置密码
	 *
	 * @param companyId     公司id
	 * @param resetPassword 重置密码
	 * @return 重置密码结果
	 */
	@Override
	public Result companyResetPassword(Long companyId, String resetPassword) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		LambdaQueryWrapper<Company> queryWrapper1 = new LambdaQueryWrapper<>();
		queryWrapper1.eq(Company::getCompanyId, companyId);
		//只查未删除的
		queryWrapper1.eq(Company::getIsDeleted, 0);
		Company company = companyMapper.selectOne(queryWrapper1);
		company.setCompanyPassword(Md5Util.getMD5String(resetPassword));
		company.setUpdateTime(DateTime.now());
		companyMapper.insertOrUpdate(company);
		//修改后踢下线
		StpUtil.logout(companyId);
		return Result.success("重置密码成功");
	}
	
	/**
	 * 餐饮公司状态修改
	 *
	 * @param companyId 公司id
	 * @param status    状态值
	 * @return 状态修改结果
	 */
	@Override
	public Result UpdateCompanyStatus(Long companyId, Integer status) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		if (status != 1 && status != 0) {
			return Result.fail("状态值有误");
		}
		
		//执行修改
		LambdaQueryWrapper<Company> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(Company::getIsDeleted, 0);
		queryWrapper1.eq(Company::getCompanyId, companyId);
		Company company = companyMapper.selectOne(queryWrapper1);
		company.setStatus(status);
		company.setUpdateTime(DateTime.now());
		companyMapper.insertOrUpdate(company);
		
		//修改相关合作关系的状态为停用
		LambdaQueryWrapper<CooperateSchoolCompany> queryWrapper2 = new LambdaQueryWrapper<>();
		//查未删除的
		queryWrapper2.eq(CooperateSchoolCompany::getIsDeleted, 0);
		//查正在合作状态的
		queryWrapper2.eq(CooperateSchoolCompany::getStatus, 1);
		queryWrapper2.eq(CooperateSchoolCompany::getCompanyId, companyId);
		List<CooperateSchoolCompany> cooperateSchoolCompanies = cooperateSchoolCompanyMapper.selectList(queryWrapper2);
		
		//存在正在合作的合作关系
		if (status == 0 && ! cooperateSchoolCompanies.isEmpty()) {
			//枚举修改
			for (CooperateSchoolCompany cooperate : cooperateSchoolCompanies) {
				cooperate.setStatus(0);
				cooperate.setUpdateTime(DateTime.now());
				cooperateSchoolCompanyMapper.insertOrUpdate(cooperate);
			}
			return Result.success("状态修改成功，注意：与该餐饮公司相关的 " + cooperateSchoolCompanies.size() + " 个合作关系都已停用");
		}
		
		return Result.success("状态修改成功");
	}
	
	/**
	 * 餐饮公司删除
	 *
	 * @param companyId 公司id
	 * @return 删除结果
	 */
	@Override
	public Result deleteCompanyById(Long companyId) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		//先查是否存在合作
		LambdaQueryWrapper<CooperateSchoolCompany> queryWrapper2 = new LambdaQueryWrapper<>();
		queryWrapper2.eq(CooperateSchoolCompany::getIsDeleted, 0);
		queryWrapper2.eq(CooperateSchoolCompany::getCompanyId, companyId);
		Long count = cooperateSchoolCompanyMapper.selectCount(queryWrapper2);
		if (count != 0) {
			return Result.fail("该餐饮公司存在 " + count + " 个合作关系，无法删除");
		}
		//假删除
		LambdaQueryWrapper<Company> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(Company::getIsDeleted, 0);
		queryWrapper1.eq(Company::getCompanyId, companyId);
		Company company = companyMapper.selectOne(queryWrapper1);
		company.setIsDeleted(1);
		company.setUpdateTime(DateTime.now());
		companyMapper.updateById(company);
		return Result.success("删除成功");
	}
	
	/**
	 * 更新餐饮公司绑定的银行账号
	 *
	 * @param companyId 餐饮公司id
	 * @param accountId 银行账号id
	 * @return 更新结果
	 */
	@Override
	public Result updateCompanyAccount(Long companyId, Long accountId) {
		
		//先查登录的账号的权限
		Long loginEducationId = StpUtil.getLoginIdAsLong();
		//构造查询
		LambdaQueryWrapper<Education> queryWrapper = new LambdaQueryWrapper<>();
		//以id作为查询依据
		queryWrapper.eq(Education::getEducationId, loginEducationId);
		//获取实例
		Education loginEducation = educationMapper.selectOne(queryWrapper);
		
		//判断权限
		if (loginEducation.getEducationPower() != 1) {
			throw new PowerFailedException("权限不足");
		}
		
		LambdaQueryWrapper<Account> queryWrapper2 = new LambdaQueryWrapper<>();
		queryWrapper2.eq(Account::getAccountId, accountId);
		queryWrapper2.eq(Account::getIsDeleted, 0);
		Account account = accountMapper.selectOne(queryWrapper2);
		if (account == null) {
			return Result.fail("该银行账号不存在");
		}
		
		LambdaQueryWrapper<Company> queryWrapper1 = new LambdaQueryWrapper<>();
		//只查未删除的
		queryWrapper1.eq(Company::getIsDeleted, 0);
		queryWrapper1.eq(Company::getCompanyId, companyId);
		Company company = companyMapper.selectOne(queryWrapper1);
		company.setAccountId(accountId);
		company.setUpdateTime(DateTime.now());
		companyMapper.insertOrUpdate(company);
		
		return Result.success("修改成功");
	}
	
	/**
	 * 统计餐饮公司数量
	 *
	 * @return 餐饮公司数量
	 */
	@Override
	public Long countCompanyNum() {
		LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Company::getIsDeleted, 0);
		return companyMapper.selectCount(queryWrapper);
	}
}
